import datetime
import requests
import re
import random
from typing import Dict, Any, Optional, List, Tuple


def get_current_time() -> str:
    """获取当前时间"""
    now = datetime.datetime.now()
    return now.strftime("%Y年%m月%d日 %H:%M:%S")


def get_current_date() -> str:
    """获取当前日期"""
    today = datetime.date.today()
    return today.strftime("%Y年%m月%d日")


def get_weather_info(city: str = "北京") -> Dict[str, Any]:
    """
    获取天气信息（模拟实现）
    在实际应用中，这里应该调用真实的天气API
    """
    # 这是一个模拟的天气数据
    weather_data = {
        "city": city,
        "temperature": "22°C",
        "weather": "晴朗",
        "humidity": "65%",
        "wind_speed": "3级",
        "air_quality": "良好",
        "forecast": "今日晴朗，适宜出行"
    }
    
    return weather_data


def search_knowledge_base(query: str) -> Optional[str]:
    """
    搜索知识库（模拟实现）
    在实际应用中，这里应该连接到真实的知识库
    """
    # 模拟知识库数据
    knowledge_base = {
        "退货政策": "我们支持7天无理由退货，商品需保持原包装完好。具体退货流程：1）联系客服申请退货；2）获得退货地址；3）寄回商品；4）审核通过后3-5个工作日退款。",
        "配送时间": "一般情况下，订单会在24小时内发货，3-5个工作日内送达。偏远地区可能需要额外1-2天。急需的话可以选择次日达服务（需额外付费）。",
        "客服时间": "我们的客服工作时间是周一至周日 9:00-18:00。客服热线：400-123-4567。也可以通过在线客服或邮箱service@example.com联系我们。",
        "支付方式": "我们支持微信支付、支付宝、银行卡、信用卡等多种支付方式。所有支付都采用SSL加密，确保您的资金安全。",
        "会员权益": "会员享有专属折扣、优先客服、生日礼品、积分翻倍、免费配送等多项权益。升级VIP会员还可享受更多特权。",
        "发票问题": "我们支持开具电子发票和纸质发票。电子发票下单后立即发送至邮箱，纸质发票需要额外1-2个工作日。可开具个人或企业发票。",
        "积分规则": "消费1元获得1积分，积分可用于兑换优惠券和礼品。积分有效期2年，VIP会员积分永久有效。签到、评价等行为也可获得积分奖励。",
        "售后服务": "产品出现质量问题，我们提供免费维修或更换服务。保修期内免费，保修期外提供有偿维修。支持全国联保，详细政策请查看商品页面。",
        "会员注册": "注册成为会员即可享受专属优惠和积分奖励。注册免费，只需提供手机号和基本信息。新用户注册即送100积分和新人专享优惠券。",
        "换货政策": "商品如有质量问题或规格不符，支持7天内免费换货。换货需保持商品完整包装，配件齐全。人为损坏不支持换货。",
        "物流配送": "我们与顺丰、京东物流等合作，提供标准配送和次日达服务。支持送货上门、自提柜、代收点等多种配送方式。",
        "价格保护": "购买后7天内如商品降价，可申请价保退差价。参与活动商品除外。VIP会员享受30天价保服务。"
    }
    
    # 智能关键词匹配 - 扩展匹配逻辑
    query_lower = query.lower()
    
    # 直接关键词匹配
    for key, value in knowledge_base.items():
        if any(keyword in query for keyword in key.split()):
            return value
    
    # 扩展关键词匹配
    keyword_mapping = {
        "退货": ["退货政策", "换货政策"],
        "退款": ["退货政策", "换货政策"],
        "换货": ["换货政策", "退货政策"],
        "配送": ["配送时间", "物流配送"],
        "物流": ["物流配送", "配送时间"],
        "发货": ["配送时间", "物流配送"],
        "快递": ["物流配送", "配送时间"],
        "客服": ["客服时间"],
        "联系": ["客服时间"],
        "电话": ["客服时间"],
        "支付": ["支付方式"],
        "付款": ["支付方式"],
        "安全": ["支付方式"],
        "会员": ["会员权益", "会员注册"],
        "积分": ["积分规则", "会员权益"],
        "发票": ["发票问题"],
        "开票": ["发票问题"],
        "售后": ["售后服务"],
        "保修": ["售后服务"],
        "维修": ["售后服务"],
        "质量": ["售后服务", "换货政策"],
        "注册": ["会员注册"],
        "价格": ["价格保护"],
        "降价": ["价格保护"],
        "优惠": ["会员权益", "价格保护"]
    }
    
    # 根据关键词映射查找
    for keyword, related_keys in keyword_mapping.items():
        if keyword in query:
            for related_key in related_keys:
                if related_key in knowledge_base:
                    return knowledge_base[related_key]
    
    return None


# ========== 智能客服功能 ==========

def analyze_customer_sentiment(message: str) -> Dict[str, Any]:
    """
    分析客户情绪
    """
    # 情绪关键词词典
    positive_words = ["满意", "好", "不错", "棒", "赞", "喜欢", "开心", "高兴", "感谢", "谢谢"]
    negative_words = ["不满意", "差", "糟糕", "垃圾", "烂", "讨厌", "愤怒", "生气", "抱怨", "投诉"]
    neutral_words = ["一般", "还行", "可以", "普通", "正常"]
    
    # 统计情绪词汇
    positive_count = sum(1 for word in positive_words if word in message)
    negative_count = sum(1 for word in negative_words if word in message)
    neutral_count = sum(1 for word in neutral_words if word in message)
    
    # 判断情绪倾向
    if negative_count > positive_count:
        sentiment = "negative"
        confidence = min(0.8, 0.5 + negative_count * 0.1)
    elif positive_count > negative_count:
        sentiment = "positive"
        confidence = min(0.8, 0.5 + positive_count * 0.1)
    else:
        sentiment = "neutral"
        confidence = 0.5
    
    return {
        "sentiment": sentiment,
        "confidence": confidence,
        "analysis": {
            "positive_indicators": positive_count,
            "negative_indicators": negative_count,
            "neutral_indicators": neutral_count
        }
    }


def categorize_customer_query(query: str) -> Dict[str, Any]:
    """
    对客户查询进行分类
    """
    categories = {
        "订单相关": ["订单", "发货", "物流", "快递", "配送", "到货", "签收"],
        "商品相关": ["商品", "产品", "质量", "规格", "参数", "功能", "使用"],
        "支付相关": ["支付", "付款", "价格", "费用", "优惠", "折扣", "促销"],
        "售后相关": ["退货", "换货", "维修", "保修", "售后", "质量问题"],
        "账户相关": ["账户", "登录", "密码", "注册", "会员", "积分"],
        "其他问题": ["客服", "咨询", "帮助", "联系方式"]
    }
    
    # 匹配分类
    matched_categories = []
    for category, keywords in categories.items():
        if any(keyword in query for keyword in keywords):
            matched_categories.append(category)
    
    # 如果没有匹配到具体分类，归为其他问题
    if not matched_categories:
        matched_categories = ["其他问题"]
    
    return {
        "categories": matched_categories,
        "primary_category": matched_categories[0],
        "confidence": 0.8 if len(matched_categories) == 1 else 0.6
    }


def handle_order_inquiry(order_id: str = None) -> Dict[str, Any]:
    """
    处理订单查询
    """
    if not order_id:
        return {
            "success": False,
            "message": "请提供订单号以查询订单状态",
            "help_text": "订单号通常是10-15位数字，可在订单确认邮件中找到"
        }
    
    # 模拟订单数据
    mock_orders = {
        "2024070300001": {
            "status": "已发货",
            "tracking_number": "SF1234567890",
            "estimated_delivery": "2024年7月5日",
            "items": ["智能手机 x1", "手机壳 x1"],
            "total_amount": "3999.00"
        },
        "2024070300002": {
            "status": "配送中",
            "tracking_number": "YTO9876543210",
            "estimated_delivery": "2024年7月4日",
            "items": ["笔记本电脑 x1"],
            "total_amount": "5999.00"
        }
    }
    
    if order_id in mock_orders:
        order_info = mock_orders[order_id]
        return {
            "success": True,
            "order_id": order_id,
            "order_info": order_info,
            "message": f"订单 {order_id} 当前状态：{order_info['status']}"
        }
    else:
        return {
            "success": False,
            "message": "未找到该订单信息，请检查订单号是否正确",
            "suggestion": "您可以登录账户查看所有订单，或联系客服获取帮助"
        }


def generate_faq_response(question: str) -> Optional[str]:
    """
    生成常见问题的回答（增强版）
    """
    # 扩展的FAQ数据库，包含更多关键词匹配
    faqs = {
        "退货": {
            "keywords": ["退货", "退款", "返回", "退掉", "不要了", "退回"],
            "answer": "退货流程：1.登录账户->我的订单->申请退货 2.填写退货原因 3.打包商品并贴上退货单 4.联系快递上门取件 5.退款将在收到商品后3-5个工作日内处理完成。"
        },
        "配送": {
            "keywords": ["配送", "发货", "物流", "快递", "送货", "多久", "时间", "几天"],
            "answer": "配送时间说明：工作日下单当天发货，周末下单周一发货。一般3-5个工作日送达，偏远地区可能需要7-10个工作日。"
        },
        "支付": {
            "keywords": ["支付", "付款", "安全", "支付宝", "微信", "银行卡"],
            "answer": "支付安全保障：我们采用SSL加密技术，支持多种安全支付方式，所有交易信息都经过加密处理，请放心支付。支持微信支付、支付宝、银行卡等多种支付方式。"
        },
        "会员": {
            "keywords": ["会员", "权益", "积分", "折扣", "优惠", "特权"],
            "answer": "会员专享权益：1.专属折扣优惠 2.生日礼品 3.积分奖励 4.优先客服服务 5.新品抢先体验 6.免费配送服务。消费1元获得1积分，积分可用于兑换优惠券和礼品。"
        },
        "发票": {
            "keywords": ["发票", "开票", "报销", "税票", "电子发票"],
            "answer": "发票开具说明：支持开具电子发票和纸质发票，请在下单时选择发票类型并填写发票信息。电子发票将在付款后24小时内发送到您的邮箱。"
        },
        "换货": {
            "keywords": ["换货", "更换", "调换", "换个"],
            "answer": "换货流程：1.登录账户申请换货 2.说明换货原因 3.退回原商品 4.我们确认后发出新商品。换货商品需保持原包装完好，7天内可申请换货。"
        },
        "保修": {
            "keywords": ["保修", "维修", "质保", "坏了", "故障", "修理"],
            "answer": "保修服务：商品享有1年质保服务，质量问题免费维修或更换。请提供购买凭证和故障描述，我们会安排专业技术人员处理。"
        },
        "客服": {
            "keywords": ["客服", "联系", "电话", "咨询", "人工"],
            "answer": "客服联系方式：电话400-123-4567，工作时间周一至周日9:00-18:00。您也可以通过在线客服、邮箱service@company.com或微信Company_Service联系我们。"
        }
    }
    
    # 先进行精确匹配
    for category, faq_data in faqs.items():
        for keyword in faq_data["keywords"]:
            if keyword in question:
                return faq_data["answer"]
    
    # 如果没有匹配到，尝试模糊匹配
    question_lower = question.lower()
    for category, faq_data in faqs.items():
        for keyword in faq_data["keywords"]:
            if keyword.lower() in question_lower:
                return faq_data["answer"]
    
    return None


def escalate_to_human_agent(issue: str, customer_info: Dict[str, Any] = None) -> Dict[str, Any]:
    """
    转接人工客服
    """
    # 生成工单号
    ticket_id = f"T{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}"
    
    return {
        "ticket_id": ticket_id,
        "status": "已转接人工客服",
        "estimated_wait_time": "预计等待时间：3-5分钟",
        "message": f"您的问题已转接给人工客服，工单号：{ticket_id}。客服将尽快为您处理，请稍候。",
        "priority": "normal",
        "created_at": get_current_time()
    }


def provide_contact_info() -> Dict[str, Any]:
    """
    提供联系方式信息
    """
    return {
        "customer_service": {
            "phone": "400-123-4567",
            "email": "service@company.com",
            "wechat": "Company_Service",
            "working_hours": "周一至周日 9:00-18:00"
        },
        "technical_support": {
            "phone": "400-123-4568",
            "email": "tech@company.com",
            "working_hours": "周一至周五 9:00-18:00"
        },
        "complaints": {
            "phone": "400-123-4569",
            "email": "complaint@company.com",
            "working_hours": "周一至周日 9:00-18:00"
        }
    }


def suggest_similar_products(product_name: str) -> List[Dict[str, Any]]:
    """
    推荐相似产品
    """
    # 模拟产品推荐数据
    product_suggestions = {
        "手机": [
            {"name": "华为P60", "price": "4999", "rating": "4.8"},
            {"name": "小米13", "price": "3999", "rating": "4.7"},
            {"name": "OPPO Find X6", "price": "4499", "rating": "4.6"}
        ],
        "电脑": [
            {"name": "联想ThinkPad", "price": "6999", "rating": "4.9"},
            {"name": "戴尔XPS13", "price": "7999", "rating": "4.8"},
            {"name": "华为MateBook", "price": "5999", "rating": "4.7"}
        ],
        "耳机": [
            {"name": "AirPods Pro", "price": "1999", "rating": "4.8"},
            {"name": "索尼WH-1000XM4", "price": "2399", "rating": "4.9"},
            {"name": "Bose QC35", "price": "2199", "rating": "4.7"}
        ]
    }
    
    # 简单的关键词匹配
    for category, products in product_suggestions.items():
        if category in product_name:
            return products
    
    # 默认推荐
    return [
        {"name": "热销商品A", "price": "299", "rating": "4.5"},
        {"name": "热销商品B", "price": "599", "rating": "4.6"},
        {"name": "热销商品C", "price": "899", "rating": "4.7"}
    ]


def track_customer_satisfaction(rating: int, feedback: str = "") -> Dict[str, Any]:
    """
    跟踪客户满意度
    """
    if not 1 <= rating <= 5:
        return {
            "success": False,
            "message": "评分必须在1-5之间"
        }
    
    satisfaction_level = {
        1: "非常不满意",
        2: "不满意", 
        3: "一般",
        4: "满意",
        5: "非常满意"
    }
    
    return {
        "success": True,
        "rating": rating,
        "level": satisfaction_level[rating],
        "feedback": feedback,
        "timestamp": get_current_time(),
        "message": "感谢您的评价，我们会持续改进服务质量！"
    }


def generate_smart_reply_suggestions(customer_message: str) -> List[str]:
    """
    生成智能回复建议
    """
    # 分析消息类型并生成相应的回复建议
    sentiment = analyze_customer_sentiment(customer_message)
    category = categorize_customer_query(customer_message)
    
    suggestions = []
    
    # 根据情绪提供回复建议
    if sentiment["sentiment"] == "negative":
        suggestions.extend([
            "非常抱歉给您带来不便，我会立即为您处理这个问题。",
            "我理解您的困扰，让我来帮您解决这个问题。",
            "感谢您的反馈，我们会认真对待并改进。"
        ])
    elif sentiment["sentiment"] == "positive":
        suggestions.extend([
            "很高兴听到您的满意反馈！",
            "谢谢您的好评，我们会继续努力！",
            "您的支持是我们前进的动力！"
        ])
    
    # 根据问题类型提供回复建议
    primary_category = category["primary_category"]
    
    if "订单" in primary_category:
        suggestions.append("请提供您的订单号，我来帮您查询订单状态。")
    elif "商品" in primary_category:
        suggestions.append("我来为您详细介绍一下这个商品的信息。")
    elif "售后" in primary_category:
        suggestions.append("我来为您处理售后问题，请详细描述遇到的情况。")
    
    return suggestions[:3]  # 返回最多3个建议


def format_response(content: str, response_type: str = "text") -> Dict[str, Any]:
    """格式化响应内容"""
    return {
        "content": content,
        "type": response_type,
        "timestamp": get_current_time(),
        "status": "success"
    }


def validate_input(user_input: str) -> bool:
    """验证用户输入"""
    if not user_input or not user_input.strip():
        return False
    
    # 检查输入长度
    if len(user_input.strip()) > 1000:
        return False
    
    return True


# ========== 工具注册 ==========

# 可用工具列表（更新后包含智能客服功能）
AVAILABLE_TOOLS = [
    {
        "name": "get_current_time",
        "description": "获取当前时间",
        "function": get_current_time
    },
    {
        "name": "get_current_date", 
        "description": "获取当前日期",
        "function": get_current_date
    },
    {
        "name": "get_weather_info",
        "description": "获取指定城市的天气信息",
        "function": get_weather_info
    },
    {
        "name": "search_knowledge_base",
        "description": "搜索知识库获取相关信息",
        "function": search_knowledge_base
    },
    # 智能客服功能
    {
        "name": "analyze_customer_sentiment",
        "description": "分析客户消息的情绪倾向",
        "function": analyze_customer_sentiment
    },
    {
        "name": "categorize_customer_query",
        "description": "对客户查询进行智能分类",
        "function": categorize_customer_query
    },
    {
        "name": "handle_order_inquiry",
        "description": "处理订单查询请求",
        "function": handle_order_inquiry
    },
    {
        "name": "generate_faq_response",
        "description": "生成常见问题的自动回答",
        "function": generate_faq_response
    },
    {
        "name": "escalate_to_human_agent",
        "description": "转接人工客服",
        "function": escalate_to_human_agent
    },
    {
        "name": "provide_contact_info",
        "description": "提供客服联系方式",
        "function": provide_contact_info
    },
    {
        "name": "suggest_similar_products",
        "description": "推荐相似产品",
        "function": suggest_similar_products
    },
    {
        "name": "track_customer_satisfaction",
        "description": "记录客户满意度评价",
        "function": track_customer_satisfaction
    },
    {
        "name": "generate_smart_reply_suggestions",
        "description": "生成智能回复建议",
        "function": generate_smart_reply_suggestions
    }
]


def get_tool_by_name(tool_name: str):
    """根据名称获取工具函数"""
    for tool in AVAILABLE_TOOLS:
        if tool["name"] == tool_name:
            return tool["function"]
    return None


def get_available_tools_description() -> str:
    """获取可用工具的描述"""
    descriptions = []
    for tool in AVAILABLE_TOOLS:
        descriptions.append(f"- {tool['name']}: {tool['description']}")
    return "\n".join(descriptions)


# ========== 智能客服流程管理 ==========

class CustomerServiceSession:
    """客服会话管理类"""
    
    def __init__(self, session_id: str):
        self.session_id = session_id
        self.start_time = datetime.datetime.now()
        self.messages = []
        self.customer_info = {}
        self.current_issue = None
        self.satisfaction_rating = None
        
    def add_message(self, message: str, sender: str = "customer"):
        """添加消息到会话历史"""
        self.messages.append({
            "content": message,
            "sender": sender,
            "timestamp": get_current_time(),
            "sentiment": analyze_customer_sentiment(message) if sender == "customer" else None
        })
    
    def get_session_summary(self) -> Dict[str, Any]:
        """获取会话摘要"""
        duration = datetime.datetime.now() - self.start_time
        return {
            "session_id": self.session_id,
            "duration_minutes": int(duration.total_seconds() / 60),
            "message_count": len(self.messages),
            "customer_satisfaction": self.satisfaction_rating,
            "issues_resolved": bool(self.current_issue),
            "start_time": self.start_time.strftime("%Y-%m-%d %H:%M:%S")
        }
